package com.yzr.common.thread.counter;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        // 计数，限流
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i < 10; i++) {
            new Thread(() -> {
                // 获得信号量
                try {
                    semaphore.acquire();
                    System.out.println("线程" + Thread.currentThread().getName() + "获得");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("线程" + Thread.currentThread().getName() + "离开");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
